package com.etc.my.controller;


import com.etc.my.dto.*;
import com.etc.my.entity.User;
import com.etc.my.service.CarService;
import com.etc.my.service.MyCollectionService;
import com.etc.my.service.impl.MyCollectionServiceImpl;
import com.etc.my.vo.SelectCarVo;
import com.etc.my.vo.MyValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
public class CarController {
    @Autowired
    private CarService cs;

    public CarService getCs() {
        return cs;
    }

    public void setCs(CarService cs) {
        this.cs = cs;
    }

    @Autowired
    private MyCollectionService colService;

    public MyCollectionService getColService() {
        return colService;
    }

    public void setColService(MyCollectionService colService) {
        this.colService = colService;
    }

    @RequestMapping("/getcarByAddress")
    @ResponseBody
    public MyMessage getcarByAddress(HttpSession session, String address, Integer page, Integer size, MyValue value) throws Exception {
        MyMessage message = new MyMessage();

        //对分页数据进行容错
        if (page == null || page <= 0) {
            page = 1;
        }

        if (size == null || size <= 0) {
            size = 8;
        }

        //方法条件对象
        value.setCar_adress("%" + address + "%");
        value.setStartindex((page - 1) * size);
        value.setSize(size);

        //获取总条数
        CountDto count = cs.getCarCount(value);
        Integer allcount = count.getAllCount();

        //求符合条件的最大页数
        Integer maxPage = (allcount % size == 0 ? (allcount / size) : (allcount / size + 1));

        //页数条数上限容错
        page = page > maxPage ? maxPage : page;
        size = size > 8 ? 8 : size;
        //页数条数下限容错
        page = page <= 0 ? 1 : page;
        size = size <= 0 ? 8 : size;


        PageDto pd = new PageDto();
        pd.setPage(page);
        pd.setSize(size);
        pd.setMaxPage(maxPage);
        try {
            List<CarMessageDto> list = cs.getCarByCondition(value);
            //查询数据封装到PageDto类中

            if (list == null || list.size() == 0) {
                message.setFlag(0);
                message.setInfo("没有相应数据");
            } else {
                pd.setAllCount(allcount);
                pd.setOlist(list);
                message.setCode("200");
                message.setFlag(1);
                message.setInfo("有相应数据");
                //把pageDto放入消息类返回给前端
                message.setData(pd);

                //将地址存入会话域
                session.setAttribute("fixcity", address);
            }
        } catch (Exception e) {
            message.setCode("500");
            message.setInfo("服务器内部异常！！！！");
        }
        return message;
    }

    /**
     * 最新上架的车
     *
     * @param address
     * @param page
     * @param size
     * @param value
     * @return
     * @throws Exception
     */
    @RequestMapping("/getcarByNewTime")
    @ResponseBody
    public MyMessage getcarByNewTime(String address, Integer page, Integer size, MyValue value) throws Exception {
        MyMessage message = new MyMessage();

        //对分页数据进行容错
        if (page == null || page <= 0) {
            page = 1;
        }

        if (size == null || size <= 0) {
            size = 8;
        }

        //方法条件对象
        value.setCar_adress("%" + address + "%");
        value.setCar_time("%" + value.getCar_time() + "%");
        value.setStartindex((page - 1) * size);
        value.setSize(size);

        //获取总条数
        CountDto count = cs.getCarCount(value);
        Integer allcount = count.getAllCount();

        //求符合条件的最大页数
        Integer maxPage = (allcount % size == 0 ? (allcount / size) : (allcount / size + 1));

        //页数条数上限容错
        page = page > maxPage ? maxPage : page;
        size = size > 8 ? 8 : size;
        //页数条数下限容错
        page = page <= 0 ? 1 : page;
        size = size <= 0 ? 8 : size;


        PageDto pd = new PageDto();
        pd.setPage(page);
        pd.setSize(size);
        pd.setMaxPage(maxPage);

        try {
            List<CarMessageDto> list = cs.getCarByCondition(value);
            //查询数据封装到PageDto类中

            if (list == null || list.size() == 0) {
                message.setFlag(0);
                message.setInfo("没有相应数据");
            } else {
                pd.setAllCount(allcount);
                pd.setOlist(list);
                message.setCode("200");
                message.setFlag(1);
                message.setInfo("有相应数据");
                //把pageDto放入消息类返回给前端
                message.setData(pd);
            }
        } catch (Exception e) {
            message.setCode("500");
            message.setInfo("服务器内部异常！！！！");
        }
        return message;
    }

    /**
     * 准新车
     * @param address
     * @param page
     * @param size
     * @param value
     * @return
     * @throws Exception
     */
    @RequestMapping("/getcarByCarMile")
    @ResponseBody
    public MyMessage getcarByCarMile( String address, Integer page, Integer size, MyValue value) throws Exception {
        MyMessage message = new MyMessage();

        //对分页数据进行容错
        if (page == null || page <= 0) {
            page = 1;
        }

        if (size == null || size <= 0) {
            size = 8;
        }

        //方法条件对象
        value.setCar_adress("%" + address + "%");
        value.setStartindex((page - 1) * size);
        value.setSize(size);

        //获取总条数
        CountDto count = cs.getCarCount(value);
        Integer allcount = count.getAllCount();

        //求符合条件的最大页数
        Integer maxPage = (allcount % size == 0 ? (allcount / size) : (allcount / size + 1));

        //页数条数上限容错
        page = page > maxPage ? maxPage : page;
        size = size > 8 ? 8 : size;
        //页数条数下限容错
        page = page <= 0 ? 1 : page;
        size = size <= 0 ? 8 : size;


        PageDto pd = new PageDto();
        pd.setPage(page);
        pd.setSize(size);
        pd.setMaxPage(maxPage);

        try {
            List<CarMessageDto> list = cs.getCarByCondition(value);
            //查询数据封装到PageDto类中

            if (list == null || list.size() == 0) {
                message.setFlag(0);
                message.setInfo("没有相应数据");
            } else {
                pd.setAllCount(allcount);
                pd.setOlist(list);
                message.setCode("200");
                message.setFlag(1);
                message.setInfo("有相应数据");
                //把pageDto放入消息类返回给前端
                message.setData(pd);
            }
        } catch (Exception e) {
            message.setCode("500");
            message.setInfo("服务器内部异常！！！！");
        }
        return message;
    }


    /**
     * 查询所有的车辆
     *
     * @return
     */
    @RequestMapping("/getAllCar")
    @ResponseBody
    public MyMessage getAllCar() {
        MyMessage message = new MyMessage();

        List<CarMessageDto> list = cs.getAllCar();
        if (list != null && list.size() > 0) {
            message.setFlag(1);
            message.setData(list);
        } else {
            message.setFlag(0);
        }
        return message;
    }


    /**
     * 查询用户卖车 的控制器
     *
     * @param session
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/getCarByUserId")
    @ResponseBody
    public Object getCarByUserId(HttpSession session, Integer page, Integer size) {
        MyMessage message = new MyMessage();
        //获取登录的用户
         User user = (User) session.getAttribute("loginuser");


        if (user != null) {
            //判断是否有取到值
            if (page == null || page <= 0) {
                page = 1;
            }

            if (size == null || size <= 0) {
                size = 3;
            }
            //获取总条数
            Integer allCount = cs.getCarCountByUserId(user.getUser_id()).getAllCount();
            if (allCount >= 0 && allCount != null) {
                Integer maxPage = (allCount % size == 0) ? (allCount / size) : (allCount / size + 1);
                //页数条数上限容错
                page = page > maxPage ? maxPage : page;
                size = size > 3 ? 3 : size;
                //页数条数下限容错
                page = page <= 0 ? 1 : page;
                size = size <= 0 ? 3 : size;

                PageDto pd = new PageDto();
                pd.setPage(page);
                pd.setSize(size);

                //调用方法查询
                List<CarMessageDto> pushList = cs.getCarByUserIdOfFage(user.getUser_id(), (page - 1) * size, size);
                if (pushList.size() > 0 && pushList != null) {
                    message.setFlag(1);
                    pd.setMaxPage(maxPage);
                    pd.setAllCount(allCount);
                    pd.setOlist(pushList);
                    message.setData(pd);
                } else {
                    message.setFlag(0);
                    message.setInfo("查无此纪录");
                }
            } else {
                message.setFlag(0);
                message.setInfo("查无此纪录");
            }

        } else {
            message.setFlag(0);
            message.setInfo("您尚未登录请先登录!");
        }

        return message;
    }

    /**
     * 根据多个条件查询车辆
     *
     * @param selectCarCondition 所有的查询条件
     * @return
     */
    @RequestMapping("/selectCarByMuplCondition")
    @ResponseBody
    public MyMessage selectCarByMuplCondition(SelectCarVo selectCarCondition) {
        MyMessage message = new MyMessage();
        if (selectCarCondition.getCar_price()!=null && ("3万内").equals(selectCarCondition.getCar_price())) {
            selectCarCondition.setCar_maxprice(3.0);
        } else if (selectCarCondition.getCar_price()!=null && selectCarCondition.getCar_price().equals("3-5万")) {
            selectCarCondition.setCar_minprice(3.0);
            selectCarCondition.setCar_maxprice(5.0);
        } else if (selectCarCondition.getCar_price()!=null && selectCarCondition.getCar_price().equals("5-8万")) {
            selectCarCondition.setCar_minprice(5.0);
            selectCarCondition.setCar_maxprice(8.0);
        } else if (selectCarCondition.getCar_price()!=null && selectCarCondition.getCar_price().equals("8-10万")) {
            selectCarCondition.setCar_minprice(8.0);
            selectCarCondition.setCar_maxprice(10.0);
        } else if (selectCarCondition.getCar_price()!=null && selectCarCondition.getCar_price().equals("10-15万")) {
            selectCarCondition.setCar_minprice(10.0);
            selectCarCondition.setCar_maxprice(15.0);
        } else if (selectCarCondition.getCar_price()!=null && selectCarCondition.getCar_price().equals("15-20万")) {
            selectCarCondition.setCar_minprice(15.0);
            selectCarCondition.setCar_maxprice(20.0);
        } else if (selectCarCondition.getCar_price()!=null && selectCarCondition.getCar_price().equals("20-30万")) {
            selectCarCondition.setCar_minprice(20.0);
            selectCarCondition.setCar_maxprice(30.0);
        } else if (selectCarCondition.getCar_price()!=null && selectCarCondition.getCar_price().equals("30-50万")) {
            selectCarCondition.setCar_minprice(30.0);
            selectCarCondition.setCar_maxprice(50.0);
        }else if (selectCarCondition.getCar_price()!=null && selectCarCondition.getCar_price().equals("50万以上")) {
            selectCarCondition.setCar_minprice(50.0);
        }
        if (selectCarCondition.getCar_mile()!=null && ("1万公里内").equals(selectCarCondition.getCar_mile())) {
            selectCarCondition.setCar_maxmile(1.0);
        } else if (selectCarCondition.getCar_mile()!=null && ("3万公里内").equals(selectCarCondition.getCar_mile())) {
            selectCarCondition.setCar_maxmile(3.0);
        } else if (selectCarCondition.getCar_mile()!=null && ("5万公里内").equals(selectCarCondition.getCar_mile())) {
            selectCarCondition.setCar_maxmile(5.0);
        } else if (selectCarCondition.getCar_mile()!=null && ("5万公里以上").equals(selectCarCondition.getCar_mile())) {
            selectCarCondition.setCar_minmile(5.0);
        }
        if(selectCarCondition.getCar_regist()!=null && ("1年内").equals(selectCarCondition.getCar_regist())){
            selectCarCondition.setCar_minregist(getLateDate(-1));
        }else if(selectCarCondition.getCar_regist()!=null && ("2年内").equals(selectCarCondition.getCar_regist())){
            selectCarCondition.setCar_minregist(getLateDate(-2));
        }else if(selectCarCondition.getCar_regist()!=null && ("3年内").equals(selectCarCondition.getCar_regist())){
            selectCarCondition.setCar_minregist(getLateDate(-3));
        }else if(selectCarCondition.getCar_regist()!=null && ("3-5年").equals(selectCarCondition.getCar_regist())){
            selectCarCondition.setCar_minregist(getLateDate(-5));
            selectCarCondition.setCar_maxregist(getLateDate(-3));
        }else if(selectCarCondition.getCar_regist()!=null && ("5-8年").equals(selectCarCondition.getCar_regist())){
            selectCarCondition.setCar_minregist(getLateDate(-8));
            selectCarCondition.setCar_maxregist(getLateDate(-5));
        }else if(selectCarCondition.getCar_regist()!=null && ("8年以上").equals(selectCarCondition.getCar_regist())){
            selectCarCondition.setCar_maxregist(getLateDate(-8));
        }

        if(selectCarCondition.getCar_dc()!=null && selectCarCondition.getCar_dc().equals("1.0升以下")){
            selectCarCondition.setCar_maxdc(1.0);
        }else if(selectCarCondition.getCar_dc()!=null && selectCarCondition.getCar_dc().equals("1.1-1.5升")){
            selectCarCondition.setCar_mindc(1.5);
            selectCarCondition.setCar_maxdc(1.1);
        }else if(selectCarCondition.getCar_dc()!=null && selectCarCondition.getCar_dc().equals("1.6-2.0升")){
            selectCarCondition.setCar_mindc(1.6);
            selectCarCondition.setCar_maxdc(2.0);
        }else if(selectCarCondition.getCar_dc()!=null && selectCarCondition.getCar_dc().equals("2.1-3.0升")){
            selectCarCondition.setCar_mindc(2.1);
            selectCarCondition.setCar_maxdc(3.0);
        }else if(selectCarCondition.getCar_dc()!=null && selectCarCondition.getCar_dc().equals("3.1升以上")){
            selectCarCondition.setCar_mindc(3.1);
         }

        System.out.println(selectCarCondition);
        Integer page=selectCarCondition.getPage();
        Integer size=selectCarCondition.getSize();
            //查询符合条件的车辆条数

        Integer allCount = cs.getCarCountByMuplCondition(selectCarCondition).getAllCount();
        if ( allCount != null && allCount >= 0) {
            Integer maxPage = (allCount % size == 0) ? (allCount / size) : (allCount / size + 1);
            //页数条数上限容错
            page = page > maxPage ? maxPage : page;
            size = size > 12 ? 12 : size;
            //页数条数下限容错
            page = page <= 0 ? 1 : page;
            size = size <= 0 ? 12 : size;
            //封装分页查询的结果，放入PageDto对象中
            PageDto pd = new PageDto();
            pd.setPage(page);
            pd.setSize(size);
            //调用方法查询
            List<CarMessageDto> list = cs.selectCarByMuplCondition(selectCarCondition, (page - 1) * size, size);
            if (list.size() > 0 && list != null) {
                message.setFlag(1);
                pd.setMaxPage(maxPage);
                pd.setAllCount(allCount);
                pd.setOlist(list);
                pd.setKeyWords(selectCarCondition);
                message.setData(pd);
            } else {
                message.setFlag(0);
                message.setInfo("未找到符合条件的车辆！");
            }
            } else {
                message.setFlag(0);
                message.setInfo("未找到符合条件的车辆！");
            }
            return message;

    }
        /**
         * 查询汽车品牌当前正在售卖的车系
         * @param car_brand 汽车品怕
         * @return 该品牌正在售卖的车系
         */
        @RequestMapping("/getCarDeptByBrand")
        @ResponseBody
        public List<CarDeptDto> getCarDeptByBrand (String car_brand){
            if (car_brand != null && car_brand != "") {
                List<CarDeptDto> list = cs.getCarDeptByBrand(car_brand);
                return list;
            }
            return null;
        }


        /**
         * 查询汽车详细信息
         * @param car_id
         * @return
         */
        @RequestMapping("/queryCarByid")
        public ModelAndView queryCarByid (HttpSession session,String car_id) throws Exception {
            ModelAndView modelAndView = new ModelAndView();
            //car_id为null 直接返回到前端buycar
            if (car_id == null) {
                modelAndView.setViewName("buycar");
                return modelAndView;
            }
            CarMessageDto carMessageDto = cs.selectOneCarById(car_id);
            //查询结果为null直接返回到 buycar
            if (carMessageDto == null) {
                modelAndView.setViewName("buycar");
                return modelAndView;
            }
            //对时间转换
            String car_time = carMessageDto.getCar_time();
            String car_regist = carMessageDto.getCar_regist();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = simpleDateFormat.parse(car_time);
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy年MM月dd日");
            String format = simpleDate.format(parse);
            carMessageDto.setCar_time(format);
            User user = (User)session.getAttribute("loginuser");
            modelAndView.addObject("carMessageDto", carMessageDto);
            modelAndView.setViewName("buy_details");
            if(user!=null && user.getUser_id()>0){
                //查询该用户对此车的收藏状态
                boolean collection_status = colService.isCollection(user.getUser_id(),car_id);
                modelAndView.addObject("collection_status", collection_status);
            }else{
                modelAndView.addObject("collection_status", null);
            }
            return modelAndView;
        }

    /**
     * 获取当前日期前几年的日期
     * @param index 前*年 (-1/-2/-3)
     * @return 过去的日期
     */
    public String getLateDate(Integer index){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, index);
        Date y = c.getTime();
        String year = format.format(y);
        return year;
    }

    @RequestMapping("/getCarBrand")
    @ResponseBody
    public List<CarDeptDto> getCarBrand(){
        List<CarDeptDto> list =cs.getCarBrand();
        return list;
    }
}
